<script lang="ts" setup>
import type { Ref } from 'vue';

import { ElMessage, ElDrawer, ElCheckboxGroup, ElCheckbox, ElButton, ElTag } from 'element-plus';
import { ref, unref } from 'vue';

import { assignRolesToUser } from '#/api/system/user';
import { $t } from '#/locales';

const emit = defineEmits(['success']);

const userId = ref('');
const userName = ref('');
const loading = ref(false);
const saving = ref(false);
const drawerVisible = ref(false);

// 所有角色列表
const allRoles = ref<any[]>([]);
// 用户已选中的角色ID
const selectedRoleIds = ref<string[]>([]);

// 获取角色列表
const fetchRoles = async () => {
  try {
    loading.value = true;
    // 使用适配器中的角色获取函数
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error($t('system.user.fetchRolesFailed'));
  } finally {
    loading.value = false;
  }
};

// 保存角色分配
const handleSave = async () => {
  try {
    if (!userId.value) {
      ElMessage.warning($t('system.user.userNotSelected'));
      return;
    }

    saving.value = true;

    await assignRolesToUser({
      userId: userId.value,
      roleIds: selectedRoleIds.value,
    });

    ElMessage.success($t('system.user.assignRolesSuccess'));
    emit('success');
    closeDrawer();
  } catch (error: any) {
    console.error('分配角色失败:', error);
    ElMessage.error(error.message || $t('ui.actionMessage.failed'));
  } finally {
    saving.value = false;
  }
};

// 关闭抽屉
function closeDrawer() {
  drawerVisible.value = false;
}

// 打开抽屉
function openDrawer(data: any) {
  userId.value = data.id || '';
  userName.value = data.userName || '';
  selectedRoleIds.value = data.roleIds || [];

  // 打开抽屉
  drawerVisible.value = true;

  // 获取角色列表
  fetchRoles();
}

defineExpose({
  setData: openDrawer,
  open: () => { drawerVisible.value = true; },
  closeDrawer
});
</script>

<template>
  <el-drawer
    v-model="drawerVisible"
    :title="$t('system.user.assignRoles')"
    size="500px"
    :destroy-on-close="true"
  >
    <template #default>
      <div class="drawer-content" v-loading="loading">
        <div class="mb-4">
          <span class="font-bold">{{ $t('system.user.userName') }}：</span>
          <span>{{ userName }}</span>
        </div>

        <div class="roles-container">
          <p class="text-base font-medium mb-2">{{ $t('system.user.selectRoles') }}</p>
          <el-checkbox-group v-model="selectedRoleIds">
            <el-checkbox
              v-for="role in allRoles"
              :key="role.value"
              :label="role.value"
              :disabled="role.disabled"
              border
            >
              {{ role.label }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </template>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="closeDrawer">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped>
.drawer-content {
  padding: 0 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 0 20px 20px;
}

.roles-container {
  margin-top: 16px;
}

.el-checkbox {
  margin-right: 20px;
  margin-bottom: 10px;
}

.el-tag {
  margin-left: 8px;
}
</style>
